﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataAccess;

namespace Portal.Code
{
    public class SessionManager
    {
        private static object obj = new object();
        private static SessionManager instance = new SessionManager();
        private static int anonymousUserId;

        public static SessionManager Instance
        {
            get { return instance; }
        }

        private static int AnoymousUserId
        {
            get
            {
                if (anonymousUserId == 0)
                {
                    lock (obj)
                    {
                        if (anonymousUserId == 0)
                        {
                            using (var db = new CompanyDicContext())
                            {
                                var user = db.Users.Where(p => p.Role == 3).FirstOrDefault();
                                if (user != null) anonymousUserId = user.Id;
                            }
                        }
                    }
                }
                return anonymousUserId;
            }
        }

        public int CurrentUserId
        {
            get
            {
                if (HttpContext.Current.Session["UserId"] == null)
                {
                    HttpContext.Current.Session["UserId"] = AnoymousUserId;
                }
                return int.Parse(HttpContext.Current.Session["UserId"].ToString());
            }
            set { HttpContext.Current.Session["UserId"] = value; }
        }
    }
}